package com.tomato.order.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tomato.order.config.AlipayConfig;
import com.tomato.order.config.ProjectUrlConfig;
import com.tomato.order.entity.OrderMaster;
import com.tomato.order.mapper.OrderMasterMapper;
import com.tomato.order.websocket.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@RestController
public class PayController {
    @Autowired
    private AlipayConfig alipayConfig;
    @Resource
    private OrderMasterMapper orderMasterMapper;
    @Resource
    private ProjectUrlConfig projectUrlConfig;

    @GetMapping("/pay")
    public String pay(@RequestParam("out_trade_no") String out_trade_no,
                      @RequestParam("subject") String subject,
                      @RequestParam("total_amount") String total_amount,
                      @RequestParam("body") String body,
                      @RequestParam("address") String address) {
        String return_url = "http://" + projectUrlConfig.getSell() + "/login?address=" + address;
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        //String out_trade_no = "订单号";
        // 订单名称，必填
        //String subject = "订单名称";
        // 付款金额，必填
        //String total_amount = "付款金额";
        // 销售产品码 必填
        String product_code = out_trade_no;
        // 订单名称，必填

        // 商品描述，可空
        //String body = "商品描述";
        // 超时时间 可空
        String timeout_express = "2h";


        AlipayClient alipayClient = new DefaultAlipayClient
                (alipayConfig.getUrl(), alipayConfig.getAppid(), alipayConfig.getRsaPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(), alipayConfig.getAlipayPublicKey(), alipayConfig.getSigntype());
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        // 封装请求支付信息
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
        model.setBody(body);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipayRequest.setBizModel(model);
        // 设置异步通知地址
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl()+"/success");
        // 设置同步地址
        alipayRequest.setReturnUrl(return_url);
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }

    //    @RequestMapping("/success")
//    public void success(){
//        log.info("支付成功");
//    }
    @RequestMapping(path = "/success", method = RequestMethod.POST, produces = "application/x-www-form-urlencoded;charset=UTF-8")
    public String success(@RequestParam Map<String, String> map) {
        if (map.get("trade_status").equals("TRADE_SUCCESS")){
            log.info("订单:" + map.get("out_trade_no") + "支付成功");
            OrderMaster orderMaster = orderMasterMapper.selectOne(new QueryWrapper<OrderMaster>().
                    eq("order_id", map.get("out_trade_no")));
            orderMaster.setPayStatus(1);
            orderMasterMapper.updateById(orderMaster);
            WebSocket.sendMessage(map.get("subject"));
        }
        return "success";
    }
}
